<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/22
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\user;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Model\GoodsskuPrice;

use Imi\Cache\CacheManager as Cache;

/**
 * 贝壳拍卖👏
 * @Auth(name="token",nologin={"get_coupons_list","get_coupons_data","index4"})
 * @Controller("/user.auction1/")
 */
class Auction1 extends AuctionBean
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];




    /**
     * 报名
     *
     * @param int $id 拍卖id
     * @return void
     * @Action
     */
    public function enroll($id)
    {
        $auction = $this->getAuctionData($id);
        if (!$auction) {
            return $this->error('没有该拍卖', '', CODE_拍卖活动不存在);
        }
        if ($auction['type_status'] != '1') {
            return $this->error('接口错误');
        }

        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_贝壳竞拍)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '2':
                $拍卖类型 = '降价拍';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_降价拍)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '3':
                $拍卖类型 = '升价拍';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_升价拍)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_降)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_升)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            default:
                # code...
                break;
        }



        if ($auction['apply_status'] != '2') {
            return $this->error('该拍卖未通过', '', CODE_该拍卖未通过);
        }

        if ($auction['status'] == '1') {
            return $this->error('还未展示', '', CODE_该拍卖不能报名);
        }

        if ($auction['status'] == '3') {
            return $this->error('已经开拍', '', CODE_该拍卖不能报名);
        }

        //status` enum('1','2','3','5','6') DEFAULT '1' COMMENT '状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架',
        if ($auction['status'] == '2') {

            //第一次报名用户减少库存
            $data2['auction_id'] = $id;
            $_报名_ = Db::name('auction_enroll')->whereEx($data2)->find();
            if (!$_报名_) {
                // $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
                // //            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!如果库存没有了,就不能进行了
                // foreach ($goods_sku_price_arr as $key => $sku_id) {
                //     $this->DecGoodsStock($sku_id, 1, '报名' . $拍卖类型 . '活动减少库存', $id);
                // }
                $this->冻结拍卖全部库存($auction, '报名' . $拍卖类型 . '活动减少库存');
            }

            //判断有没有报名过
            $data['user_id'] = $user_id = $this->auth->user()->id;
            $data['auction_id'] = $id;
            $res = Db::name('auction_enroll')->whereEx($data)->find();
            if ($res) {
                return $this->error('您已报名该拍卖活动了', '', CODE_您已报名该拍卖活动);
            }




            //扣除贝壳
            if ($this->auth->user()->score < $auction['enroll_score']) {
                return $this->error('报名贝壳不足', $auction['enroll_score'], CODE_贝壳不足);
            }
            $this->DecUserScore($user_id, (float)$auction['enroll_score'], '报名' . $拍卖类型, 20, $id);
            $this->IncUserFreeze($user_id, 'score', (float)$auction['enroll_score'], 'auction_enroll', $id, '报名' . $拍卖类型, null, $auction['id']);
            //加入报名


            $data['time'] = time();
            $data['score'] = $auction['enroll_score'];
            $data['return_status'] = '1'; //状态:1=未退贝壳,2=已退
            Db::name('auction_enroll')->insert($data);
            $_报名状态缓存_ = 'auction_enroll_' . (string)$id . '_user_id' . (string)$user_id;
            Cache::set('redis', $_报名状态缓存_, true);

            //判断开始人数
            if ($auction['start_status'] == 'number') {
                //获取报名总人数
                $count = Db::name('auction_enroll')->where('auction_id', '=', $id)->count();
                if ($count >= $auction['enroll_num']) {
                    //开始拍卖活动
                    var_dump('贝壳竞拍-人数-报名已满', $count);
                    $end_time = time() + $auction['end_s'];
                    //修改状态              //状态:1=待展示,2=预展示,3=进行中,5=完成结束,6=已下架,7=流拍
                    Db::name('auction')->where('id', '=', $id)->update(['updatetime' => time(), 'status' => '3', 'end_time' => $end_time, 'start_time' => time()]);

                    $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                    $message = new \Imi\Queue\Model\Message;
                    //发布对列
                    $message->setMessage(json_encode(['type' => 'auction_finish' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                    $queue->push($message, (float)$auction['end_s']);




                    //推送开始拍卖
                    //推送到拍卖群组里面信息
                    $auction_start_data = ['auction_id' => $id, 'end_date' => date('Y-m-d H:i:s', $end_time), 'type_status' => $auction['type_status']];
                    $ToGroup_data = $this->ws_success('开始贝壳竞拍卖', $auction_start_data, 'auction_start');
                    \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
                    \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据
                }
            }

            //推送开始拍卖
            //推送到拍卖群组里面信息
            if ($auction['start_status'] == 'number') {
                $拍卖报名信息WS = ['auction_id' => $id, 'start_status' => $auction['start_status'], 'number_num' => $count, 'type_status' => $auction['type_status']];
            } else {
                $拍卖报名信息WS = ['auction_id' => $id, 'start_status' => $auction['start_status'], 'type_status' => $auction['type_status']];
            }

            $ToGroup_data = $this->ws_success('拍卖报名', $拍卖报名信息WS, 'auction_enroll');
            \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
            \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据

            return $this->success('报名成功');
        } else {
            return $this->error('该拍卖不能报名', '', CODE_该拍卖不能报名);
        }
    }



    /**
     * 助拍出价
     *
     * @param int $id 拍卖id
     * @param int $user_id 帮助用户ID
     * @param int $version 版本
     * @param float $multiple_price 出价格4选1非最终价
     * @param int $goods_sku_price_id 规格id
     * @param float $price 出价
     * @Action
     * @return void
     */
    public function help_offer(?int $id,  ?float $price, ?float $multiple_price, ?int $goods_sku_price_id = null, ?int $version = null, ?int $user_id = null)
    {

        //判断身份
        if ($this->auth->user()->set_id > 3) {
            $this->error('您好,你的身份不能助拍哦', $this->auth->user()->set_id);
        }

        // 
        $multiple = 1;



        $auction = $this->getAuctionData($id);
        if (!$auction) {
            return $this->error('没有该活动', $id, CODE_拍卖活动不存在);
        }



        // $temp_price = $price - $multiple_price * $multiple;
        // if ($temp_price != $auction['now_price']) {
        //     return $this->error('价格校验错误');
        // }


        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }



        if ($auction['version'] != $version) {
            return $this->error('版本号不一样', $auction['version']);
        }

        if ($auction['type_status'] != '1') {
            return $this->error('接口错误');
        }
        if (!$user_id) {
            return $this->error('帮谁拍?');
        }

        $auction_offer =  Db::name('auction_offer')->where('auction_id', '=', $id)->where('user_id', '=', $user_id)->find();
        if (!$auction_offer) {
            $this->error('没找到该用户的出价');
        }



        //限高价判断
        if ($auction['max_price'] > 0 && $price > $auction['max_price']) {
            return $this->error('超过限高价', $auction['max_price'], CODE_超过限高价);
        }

        //判断活动开始没有
        if ($auction['status'] != '3') {
            return $this->error('非进行中', '', CODE_该拍卖非进行中);
        }



        if ($auction['end_time'] < time()) {
            return $this->error('活动结束', '', CODE_该拍卖活动结束);
        }

        //检验该用户 是否还可以助拍
        $校验用户是否可以助拍 = $this->校验用户是否可以助拍($user_id, $auction['id']);
        if ($校验用户是否可以助拍 != 'ok') {
            return  $this->error('你已经助拍过');
        }





        $data['help_user_id'] = $this->auth->user()->id;

        //判断报名
        $_报名状态缓存_ = 'auction_enroll_' . (string)$id . '_user_id' . (string)$user_id;
        $_报名状态_ = Cache::get('redis', $_报名状态缓存_);
        if (!$_报名状态_) {
            $_报名状态存在_ = Cache::has('redis', $_报名状态缓存_);
            if (!$_报名状态存在_) {
                $data['user_id'] = $user_id;
                $data['auction_id'] = $id;
                $_报名状态res_ = Db::name('auction_enroll')->whereEx($data)->find();
                if ($_报名状态res_) {
                    Cache::set('redis', $_报名状态缓存_, true);
                    $_报名状态_ = true;
                } else {
                    Cache::set('redis', $_报名状态缓存_, false);
                    $_报名状态_ = false;
                }
            }
        }

        //贝壳Line_number
        $shell = $auction['shell_multiple'] * $multiple;


        $version = $auction['version'] + rand(10, 100);

        $this->UpdateFirst($id, $user_id, $version);




        //插入出价
        $data['user_id'] = $user_id;
        $data['shell'] = $shell;
        $data['auction_id'] = $id;
        $data['sort'] = Db::name('auction_offer')->where('auction_id', '=', $id)->count() + 1;
        $data['price'] = $price;
        $data['goods_sku_price_id'] = $goods_sku_price_id;
        $data['time'] = $this->time();
        $data['type_status'] = $auction['type_status'];
        $data['enroll_status'] = $_报名状态_ ? '2' : '1';
        $data['status'] = '1';
        $data['id'] =  Db::name('auction_offer')->insert($data)->getLastInsertId();

        $this->DecUserShell($user_id, $data['shell'], $拍卖类型 . $id . '出价', 22, $data['id']);




        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
        $message = new \Imi\Queue\Model\Message;
        //发布对列
        $message->setMessage(json_encode(['type' => 'auction_out' . $auction['type_status'], 'data' => ['id' => $data['id']], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
        $queue->push($message);
        //修改结束时间
        $end_time = time() + (int)config('auction_final_time');
        Db::name('auction')->where('id', '=', $auction['id'])->update(['now_price' => $price, 'end_time' => $end_time]);


        $user = $this->GetUserData1($user_id);
        //推送到拍卖群组里面信息 出价
        $user = ['nickname' => $user['nickname'], 'avatar' => $user['avatar'], 'id' => $user_id];
        $ToGroup_data = $this->ws_success(
            '出价',
            [
                'price' => $price,
                'version' => $version,
                'end_s' => (int)config('auction_final_time'),
                'end_date' => date('Y-m-d H:i:s', $end_time),
                'auction_id' => $id,
                'user' => $user,
                'enroll_status' => $_报名状态_ ? '2' : '1',
                'count' => Db::name('auction_offer')->where('auction_id',         '=',         $id)->count(),
                'sort' => $data['sort'],
                'date' => date('m.d H:i:s'),
                'type_status' => $auction['type_status']
            ],
            'auction_offer'
        );
        \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
        \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据



           //最后几分钟更新
        //推送到拍卖群组里面信息
        $auction_update_end_time_data = ['auction_final_time' => config('auction_final_time'), 'end_date' => date('Y-m-d H:i:s', $end_time), 'id' => $this->auth->user()->id, 'type_status' => $auction['type_status'], 'auction_id' => $id];
        $ToGroup_data = $this->ws_success('贝壳竞拍更新结束时间', $auction_update_end_time_data, 'auction_update_end_time');
        \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
        \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据






        $this->success('助拍成功');
    }


    /**
     * 分享拍卖
     *
     * @param int $auction_id 拍卖id
     * @param int $goods_sku_price_id 规格id
     * @Action 
     * @return void
     */
    public function share($auction_id, $goods_sku_price_id = null)
    {
        $user_id = $this->auth->user()->id;
        $data['user_id'] = $user_id;
        $data['type'] = 'auction_help';
        $data['public_id'] = $auction_id;

        $res = Db::name('share')->whereEx($data)->find();
        if ($res) {
            return $this->success('已分享过', $res);
        } else {

            $auction = $this->getAuctionData($auction_id);
            $code = base64_encode((string)$this->取最大分享码());
            $data['code'] = $code;
            $data['content'] = $auction['title'] . '分享码[' . $code . ']';
            $data['url'] = 'http:\\h5.pddds.cn\share\auction\auction_help?id=' . $auction_id;
            $data['time'] = time();
            $data['params'] = json_encode(['goods_sku_price_id' => $goods_sku_price_id]);
            $data['id'] = Db::name('share')->insert($data)->getLastInsertId();
           
        }
        return $this->success('分享', $data);
    }

    public function 取最大分享码()
    {
        return Db::name('share')->max('id') ?? 0 + 1;
    }



    /**
     * 校验用户是否可以助拍
     * 
     * @param int $user_id 用户id
     * 
     */
    public function 校验用户是否可以助拍($user_id, $auction_id = null)
    {
        $开始时间 = strtotime(date('Y-m-d'));
        $结束时间 = $开始时间 + 86400;
        $res = Db::name('auction_offer')->where('help_user_id', '=', $user_id)->where('time', '>', $开始时间)->where('time', '<', $结束时间)->find();
        if (!$res) {
            return 'ok';
        }
        return '今日已助拍';
    }



    /**
     * 出价
     *
     * @param int $id 拍卖id
     * @param int $multiple 倍数
     * @param int $goods_sku_price_id 商品规格
     * @param float $multiple_price 出价格4选1非最终价
     * @param float $price 出价
     * @param int $version 版本
     * @Action
     * @return void
     */
    public function offer(?int $id, ?int $goods_sku_price_id = null, ?int $multiple = 1, ?float $price, ?float $multiple_price, ?int $version = null)
    {


        $_当前拍卖缓存_ = 'auction_' . (string)$id;
        // $auction = Cache::get('redis', $_当前拍卖缓存_);
        // if (!$auction) {
        $auction = $this->getAuctionData($id);
        if (!$auction) {
            return $this->error('没有该活动', $id, CODE_拍卖活动不存在);
        }
        // if ($auction['cut_status'] != '3') {
        //     return $this->error('非加价拍');
        // }

        Cache::set('redis', $_当前拍卖缓存_, $auction, 1);
        // }
        if ($auction['version'] != $version) {
            return $this->error('版本号不一样', $auction['version']);
        }

        if ($auction['type_status'] != '1') {
            return $this->error('接口错误');
        }


        $验证这个规格 = $this->验证拍卖是否有这个规格($auction,  $goods_sku_price_id);
        if ($验证这个规格 != 'ok') {
            return $this->error($验证这个规格);
        }

        $temp_price = $price - $multiple_price * $multiple;
        if ($temp_price != $auction['now_price']) {
            return $this->error('价格校验错误');
        }




        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }
        if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_降价拍)) {
            return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
        }


        //限高价判断
        if ($auction['max_price'] > 0 && $price > $auction['max_price']) {
            return $this->error('超过限高价', $auction['max_price'], CODE_超过限高价);
        }

        //判断活动开始没有
        if ($auction['status'] != '3') {
            return $this->error('非进行中', '', CODE_该拍卖非进行中);
        }



        if ($auction['end_time'] < time()) {
            return $this->error('活动结束', '', CODE_该拍卖活动结束);
        }

        //最后3分钟

        if (($auction['end_time'] - config('auction_final_time')) < time()) {
            //重新计时
            Db::name('auction')->where('id', '=', $id)->update(['end_time' => time() + config('auction_final_time')]);
            // 修改最终时间
            //从现在加时间
            //修改队列结束时间

            //活动结束
            $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
            $message2 = new \Imi\Queue\Model\Message;
            //发布对列
            $message2->setMessage(json_encode(['type' => 'auction_finish' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
            $queue2->push($message2, (float)config('auction_final_time'));
        }




        $user_id = $this->auth->user()->id;

        //判断报名
        $_报名状态缓存_ = 'auction_enroll_' . (string)$id . '_user_id' . (string)$user_id;
        $_报名状态_ = Cache::get('redis', $_报名状态缓存_);
        if (!$_报名状态_) {
            $_报名状态存在_ = Cache::has('redis', $_报名状态缓存_);
            if (!$_报名状态存在_) {
                $data['user_id'] = $user_id;
                $data['auction_id'] = $id;
                $_报名状态res_ = Db::name('auction_enroll')->whereEx($data)->find();
                if ($_报名状态res_) {
                    Cache::set('redis', $_报名状态缓存_, true);
                    $_报名状态_ = true;
                } else {
                    Cache::set('redis', $_报名状态缓存_, false);
                    $_报名状态_ = false;
                }
            }
        }








        $_第一名缓存_ = 'auction_first_user_id' . (string)$id;
        $_当前价格缓存_ = 'auction_price_' . (string)$id;


        if (!Cache::has('redis', $_第一名缓存_)) {
            //第一次报名用户减少库存
            $data2['auction_id'] = $id;
            $_报名_ = Db::name('auction_enroll')->whereEx($data2)->find();
            if (!$_报名_) {
                // $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
                // foreach ($goods_sku_price_arr as $key => $sku_id) {
                //     $this->DecGoodsStock($sku_id, 1, '出价' . $拍卖类型 . '活动减少库存', $id);
                // }
                $this->冻结拍卖全部库存($auction, '出价' . $拍卖类型 . '活动减少库存');
            }
        }


        //判断用户出价的价格是否最高
        //缓存读当前价格判断  如果最高修改缓存 加入数据库  否则直接返回出价失败
        if (Cache::has('redis', $_当前价格缓存_)) {
            $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
        } else {
            $_当前价格_ = (float)$auction['now_price'];
        }


        if ($_当前价格_ >= $price) {
            return $this->error('不能低于当前拍卖价', $_当前价格_, CODE_低于当前拍卖价);
        }



        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }




        //贝壳Line_number
        $shell = $auction['shell_multiple'] * $multiple;

        //判断用户贝壳 够修改价格  扣除贝壳 加入报名
        if ($this->auth->user()->shell < $shell) {
            return $this->error('保证金不足', '', CODE_保证金不足);
        }



        Cache::set('redis', $_当前价格缓存_, $price);   //设置当前最高价格
        Cache::set('redis', $_第一名缓存_, $user_id);   //设置第一名用户

        $_第一名用户id_ = Cache::get('redis', $_第一名缓存_);
        if ($_第一名用户id_) {
            if ($_第一名用户id_ != $user_id) {
                //修改领先人

            }
        }
        $version = $auction['version'] + rand(10, 100);

        $this->UpdateFirst($id, $user_id, $version);











        //插入出价
        $data['user_id'] = $user_id;
        $data['shell'] = $shell;
        $data['auction_id'] = $id;
        $data['sort'] = Db::name('auction_offer')->where('auction_id', '=', $id)->count() + 1;
        $data['price'] = $price;
        $data['goods_sku_price_id'] = $goods_sku_price_id;
        $data['time'] = $this->time();
        $data['type_status'] = $auction['type_status'];
        $data['enroll_status'] = $_报名状态_ ? '2' : '1';
        $data['status'] = '1';
        $data['id'] =  Db::name('auction_offer')->insert($data)->getLastInsertId();

        $this->DecUserShell($user_id, $data['shell'], $拍卖类型 . $id . '出价', 22, $data['id']);

        // $this->DecUserSurety($user_id, $auction['buyer_surety'], $拍卖类型 . $id . '出价', $拍卖类型, $data['id']);
        // $this->IncUserFreeze($user_id, 'surety', $auction['buyer_surety'], 'auction2_surety', $data['id'], $拍卖类型 . $id . '出价'); //冻结保证金

        //加入对列 修改在此时间之后且 此id以后的全出局,解冻保证金


        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
        $message = new \Imi\Queue\Model\Message;
        //发布对列
        $message->setMessage(json_encode(['type' => 'auction_out' . $auction['type_status'], 'data' => ['id' => $data['id']], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
        $queue->push($message);
        //修改结束时间
        $end_time = time() + (int)config('auction_final_time');
        Db::name('auction')->where('id', '=', $auction['id'])->update(['now_price' => $price, 'end_time' => $end_time]);


        //推送到拍卖群组里面信息 出价
        $user = ['nickname' => $this->auth->user()->nickname, 'avatar' => $this->auth->user()->avatar, 'id' => $this->auth->user()->id];
        $ToGroup_data = $this->ws_success(
            '出价',
            [
                'price' => $price,
                'version' => $version,
                'end_s' => (int)config('auction_final_time'),
                'end_date' => date('Y-m-d H:i:s', $end_time),
                'auction_id' => $id,
                'user' => $user,
                'enroll_status' => $_报名状态_ ? '2' : '1',
                'count' => Db::name('auction_offer')->where('auction_id',         '=',         $id)->count(),
                'sort' => $data['sort'],
                'date' => date('m.d H:i:s'),
                'type_status' => $auction['type_status']
            ],
            'auction_offer'
        );
        \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
        \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据



             //最后几分钟更新
        //推送到拍卖群组里面信息
        $auction_update_end_time_data = ['auction_final_time' => config('auction_final_time'), 'end_date' => date('Y-m-d H:i:s', $end_time), 'id' => $this->auth->user()->id, 'type_status' => $auction['type_status'], 'auction_id' => $id];
        $ToGroup_data = $this->ws_success('贝壳竞拍更新结束时间', $auction_update_end_time_data, 'auction_update_end_time');
        \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
        \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据



        //判断限高价 如果达到限高价就结束
        // if ($auction['max_price'] > 0) {
        //     if (($price + $auction['plus_price']) >= $auction['max_price']) {
        //         Db::name('auction')->where('id', '=', $auction['id'])->update(['max_price_status' => '2']); //修改最高限高价

        // //活动结束
        // $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
        // $message2 = new \Imi\Queue\Model\Message;
        // //发布对列
        // $message2->setMessage(json_encode(['type' => 'auction_finish' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
        // $queue2->push($message2, (float)config('auction_final_time'));
        //     }
        // }

        // Cache::set('redis', 'auction_first_user_id' . (string)$id, 'value');
        //判断是否已经出价
        // Db::name('auction_offer')->where('id','=',$id)->order('ti');
        return $this->success('出价成功');
    }






    /**
     * 获取出价记录列表
     *
     * @param int $auction_id 拍卖id
     * @param integer $page 1
     * @param integer $limit 10
     * @Action
     * @return void
     */
    public function get_offer_list($auction_id, ?int $page = 1, ?int $limit = 10)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['auction_id'] = $auction_id;

        $first = Db::name('auction_offer')->whereEx($where)->orderRaw('id desc')->find();
        if ($first) {
            $first['user'] = $this->GetUserData1($first['user_id']);
            $first['date'] = date('m.d H:i:s', (int)round($first['time'] / 10000));
        }

        $count = Db::name('auction_offer')->whereEx($where)->count();
        $list = Db::name('auction_offer')->whereEx($where)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
        foreach ($list as $key => &$val) {
            $val['enroll'] = Db::name('auction_enroll')->where('user_id', '=', $val['user_id'])->whereEx($where)->find();
            $val['user'] = $this->GetUserData1($val['user_id']);
            $val['date'] = date('m.d H:i:s', (int)round($val['time'] / 10000));
        }

        return $this->success('出价列表', ['list' => $list, 'count' => $count ? $count : 0, 'first' => $first]);
    }


    /**
     * 获取用户信息头像昵称
     *
     * @param int $id 用户id
     * @return void
     */
    protected function GetUserData1($id)
    {
        return Db::name('user')->where('id', '=', $id)->fieldRaw('nickname,avatar')
            // ->cache($this->db_cache_set)
            ->find();
    }




    /**
     * 获取毫秒时间戳
     *
     * @return int
     */
    private function time()
    {
        return microtime(true) * 10000;
    }




    /**
     * 更新第一
     *
     * @param int $id
     * @param int $user_id
     * @return void
     */
    private function UpdateFirst($id, $user_id, $version)
    {
        Db::name('auction')->where('id', '=', $id)->update(['user_id' => $user_id, 'version' => $version]);
    }


    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function getAuctionData($id)
    {
        $auction = Db::name('auction')->where('id', '=', $id)->find();
        return $auction;
    }
}
